package edu.zut.main.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.*;

/**
 * JDBC操作模板
 */
public class DBUtils2 {

    static DataSource dataSource = null;
    static {
        dataSource = new ComboPooledDataSource("mysql");
    }

    static Connection connection = null;
    static PreparedStatement statement = null;
    static ResultSet resultSet = null;
    /**
     * 数据库连接的获取
     * @return 数据库连接
     */
    public static Connection getConn(){
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 查询的统一封装：
     * @param sql: 查询的sql语句
     * @param objs: sql中需要填充的数据
     * @return ResultSet: 结果集
     */
    public static ResultSet query(String sql,Object... objs){
        connection = getConn();
        //预处理sql
        try {
            statement = connection.prepareStatement(sql);
            if (null != objs && objs.length > 0){
                for (int i = 0; i < objs.length; i++) {
                    statement.setObject(i + 1,objs[i]);
                }
            }
            //执行sql
            resultSet = statement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }

    /**
     * 增删改的封装
     * @param sql: 查询的sql语句
     * @param objs: sql中需要填充的数据
     * @return int: 受影响的行数
     */
    public static int update(String sql,Object... objs){
        connection = getConn();
        int result = 0;
        try {
            //预处理sql
            statement = connection.prepareStatement(sql);
            if (null != objs && objs.length > 0){
                for (int i = 0; i < objs.length; i++) {
                    statement.setObject(i + 1,objs[i]);
                }
            }
            //执行sql
            result = statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    //如果想对结果集进行统一再次封装，可以尝试使用反射完成





}
